package com.example.myapplication.fragments;

import android.widget.Toast;
import com.example.myapplication.network.RetrofitClient;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.CategoryListActivity;
import com.example.myapplication.CourseDetailActivity;
import com.example.myapplication.R;
import com.example.myapplication.adapters.BannerPagerAdapter;
import com.example.myapplication.adapters.CategoryAdapter;
import com.example.myapplication.adapters.CourseAdapter;
import com.example.myapplication.models.Banner;
import com.example.myapplication.models.Category;
import com.example.myapplication.models.Course;
import com.example.myapplication.network.MockApiService;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class HomeFragment extends Fragment {

    private RecyclerView rvBanner;
    private RecyclerView rvCategories;
    private RecyclerView rvCourses;
    private TextView tvSectionTitle;

    private BannerPagerAdapter bannerAdapter;
    private CategoryAdapter categoryAdapter;
    private CourseAdapter courseAdapter;

    private MockApiService mockApiService;
    private Handler handler;
    private Timer timer;
    private int currentBannerPosition = 0;

    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initViews(view);
        initData();
        setupBanner();
        setupCategories();
        setupCourses();
        startBannerAutoScroll();
    }

    private void initViews(View view) {
        rvBanner = view.findViewById(R.id.rv_banner);
        rvCategories = view.findViewById(R.id.rv_categories);
        rvCourses = view.findViewById(R.id.rv_courses);
        tvSectionTitle = view.findViewById(R.id.tv_section_title);
    }

    private void initData() {
        mockApiService = new MockApiService();
        handler = new Handler(Looper.getMainLooper());
    }

    private void setupBanner() {
        RetrofitClient.getInstance().getBanners(new RetrofitClient.ApiCallback<List<Banner>>() {
            @Override
            public void onSuccess(List<Banner> banners) {
                LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(),
                        LinearLayoutManager.HORIZONTAL, false);
                rvBanner.setLayoutManager(layoutManager);

                bannerAdapter = new BannerPagerAdapter(banners, HomeFragment.this::onBannerClick);
                rvBanner.setAdapter(bannerAdapter);

                // 设置初始位置为中间，实现无限轮播
                currentBannerPosition = Integer.MAX_VALUE / 2;
                rvBanner.scrollToPosition(currentBannerPosition);
            }

            @Override
            public void onError(String message) {
                // 处理错误情况
                Toast.makeText(getContext(), "加载轮播图失败: " + message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupCategories() {
        RetrofitClient.getInstance().getCategories(new RetrofitClient.ApiCallback<List<Category>>() {
            @Override
            public void onSuccess(List<Category> categories) {
                GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 4);
                rvCategories.setLayoutManager(layoutManager);

                categoryAdapter = new CategoryAdapter(categories, HomeFragment.this::onCategoryClick);
                rvCategories.setAdapter(categoryAdapter);
            }

            @Override
            public void onError(String message) {
                Toast.makeText(getContext(), "加载分类失败: " + message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupCourses() {
        RetrofitClient.getInstance().getRecommendedCourses(new RetrofitClient.ApiCallback<List<Course>>() {
            @Override
            public void onSuccess(List<Course> courses) {
                GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
                rvCourses.setLayoutManager(layoutManager);

                courseAdapter = new CourseAdapter(courses, HomeFragment.this::onCourseClick);
                rvCourses.setAdapter(courseAdapter);

                tvSectionTitle.setText("推荐课程");
            }

            @Override
            public void onError(String message) {
                Toast.makeText(getContext(), "加载推荐课程失败: " + message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void startBannerAutoScroll() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.post(() -> {
                    currentBannerPosition++;
                    rvBanner.smoothScrollToPosition(currentBannerPosition);
                });
            }
        }, 3000, 3000); // 3秒后开始，每隔3秒执行
    }

    private void onBannerClick(Banner banner) {
        Intent intent = new Intent(getActivity(), CourseDetailActivity.class);
        intent.putExtra("course_id", banner.getCourseId());
        startActivity(intent);
    }

    private void onCategoryClick(Category category) {
        Intent intent = new Intent(getActivity(), CategoryListActivity.class);
        intent.putExtra("category_id", category.getId());
        intent.putExtra("category_name", category.getName());
        startActivity(intent);
    }

    private void onCourseClick(Course course) {
        Intent intent = new Intent(getActivity(), CourseDetailActivity.class);
        intent.putExtra("course_id", course.getId());
        startActivity(intent);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
}